package com.enation.app.shop.front.policyInsurance.adminController;

import com.enation.app.base.core.model.Member;
import com.enation.app.base.core.service.IMemberManager;
import com.enation.app.shop.core.goods.model.Goods;
import com.enation.app.shop.core.goods.service.IGoodsManager;
import com.enation.app.shop.core.goods.service.IProductManager;
import com.enation.app.shop.core.order.model.Order;
import com.enation.app.shop.core.order.model.OrderItem;
import com.enation.app.shop.core.order.service.IOrderManager;
import com.enation.app.shop.core.order.service.OrderStatus;
import com.enation.app.shop.front.api.utils.IdCardUtil;
import com.enation.app.shop.front.api.inpolicy.entity.InPolicy;
import com.enation.app.shop.front.api.inpolicy.service.IInpolicyManager;
import com.enation.eop.sdk.utils.StaticResourcesUtil;
import com.enation.framework.action.JsonResult;
import com.enation.framework.database.IDaoSupport;
import com.enation.framework.util.DateUtil;
import com.enation.framework.util.JsonResultUtil;
import net.sf.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.sql.Timestamp;
import java.util.*;

/**
 * 商业险保单
 */
@Scope("prototype")
@Controller
@RequestMapping("/app/warranty")
public class InPolicyAppController {


    @Autowired
    private IInpolicyManager inpolicyManager;
    @Autowired
    private IDaoSupport daoSupport;
    @Autowired
    private IProductManager productManager;
    @Autowired
    private IOrderManager orderManager;
    @Autowired
    private IMemberManager memberManager;
    @Autowired
    private IGoodsManager goodsManager;


    //通过userid得到保单列表
    @ResponseBody
    @RequestMapping("/getwarrantybyuserid")
    public JsonResult getListWarantyByUserid(int userid){
        List<InPolicy> warrantyList=  inpolicyManager.getWarrantyByuserid(userid);
        return JsonResultUtil.getObjectMessageJson(warrantyList,"通过userid得到保单列表");
    }


    //创建保单
    @ResponseBody
    @RequestMapping("/createwarranty")
    public JsonResult createWarranty(HttpServletRequest request) {
        String ds = request.getParameter("policyInfo");
        System.out.println(ds);
        JSONObject jsonObject = JSONObject.fromObject(ds);
        InPolicy warranty1 = new InPolicy();
        warranty1.setGoods_id(Integer.parseInt(jsonObject.get("goods_id").toString()));
        Integer goodsid=Integer.parseInt(jsonObject.get("goods_id").toString());
        warranty1.setGoods_name( goodsManager.getGoods(goodsid).getName());
        warranty1.setWarranty_number(createSn());
        warranty1.setUser_id(Integer.parseInt(jsonObject.get("user_id").toString()));
        warranty1.setApplicant_name(jsonObject.get("applicant_name").toString());
        warranty1.setMonthnumber(Integer.parseInt(jsonObject.get("monthnumber").toString()));
        if (jsonObject.get("policy_mobile").toString().length()!=11){
            return JsonResultUtil.getErrorJson("手机号码长度应该为11位");
        }
        if (!IdCardUtil.validate(jsonObject.get("policy_idcard").toString())){
            return JsonResultUtil.getErrorJson("请输入正确的身份证号码");
        }
        warranty1.setPolicy_mobile(jsonObject.get("policy_mobile").toString());
        warranty1.setPolicy_idcard(jsonObject.get("policy_idcard").toString());
        warranty1.setPolicy_address(jsonObject.get("policy_address").toString());
        try {
            warranty1.setInsurant_name(jsonObject.get("insurant_name").toString());
        }catch (Exception e){
           warranty1.setInsurant_name("");
        }
        int insured_quantity=Integer.parseInt(jsonObject.get("insured_quantity").toString());
        warranty1.setInsured_quantity(insured_quantity);
        String pid=jsonObject.get("pid").toString();
        double insurantprice=productManager.get(Integer.parseInt(pid)).getPrice();
        BigDecimal bigDecimal3=new BigDecimal(insurantprice);
        warranty1.setInsured_price(insurantprice);
        BigDecimal bigDecimal2=new BigDecimal(jsonObject.get("insured_price").toString());
        BigDecimal bigDecimal4=new BigDecimal(jsonObject.getDouble("max_premium_amount"));
        warranty1.setMax_premium_amount(bigDecimal4);
//        try {
//            Timestamp timestamp=new Timestamp(Long.parseLong(jsonObject.get("effective_time").toString()));
//            warranty1.setEffective_time(timestamp);
//        }catch (Exception e){
//            //warranty1.setEffective_time(new Timestamp(0L));
//        }
//        warranty1.setEffective_month(jsonObject.get("effective_month").toString());
        //warranty1.setCount(Integer.parseInt(jsonObject.get("count").toString()));
        BigDecimal bigDecimal1 = new BigDecimal(insured_quantity);
        Double countprice = bigDecimal2.multiply(bigDecimal1).doubleValue();
        BigDecimal bigDecimal5= new BigDecimal(countprice);
        warranty1.setPremium_amount(bigDecimal5);
        warranty1.setCreated_at(new Timestamp(System.currentTimeMillis()));
        warranty1.setUpdate_time(new Timestamp(System.currentTimeMillis()));
        warranty1.setCheck_status(0);//商业险状态（0：刚提交未审核1：审核通过2：拒绝）
        warranty1.setIs_policy(0);//0商业险   1政策险
        int i = inpolicyManager.createWarranty(warranty1);
        if (i!=1) {
            return JsonResultUtil.getErrorJson("创建保单失败");
        } else {
            return JsonResultUtil.getObjectMessageJson(warranty1.getWarranty_number(), "创建保单成功，返回保单编号");
        }
    }

    //保单/订单支付

    //查看保单详情
    @ResponseBody
    @RequestMapping("/getWarrantyDetail")
    public  JsonResult getWarrantyById(String warrantynumber){
        InPolicy warranty=inpolicyManager.warranty(warrantynumber);
        if(warranty==null){
            return JsonResultUtil.getErrorJson("查看保单详情失败");
        }else {
            Goods goods = goodsManager.getGoods(warranty.getGoods_id());
            String goodsname = goods.getName();
            warranty.setItem(goodsname);
            if (warranty.getBegin_time() == null) {
                return JsonResultUtil.getObjectMessageJson(warranty, "查看保单详情");
            } else {
                long now = new Date().getTime();
                if (now > warranty.getBegin_time().getTime()+24*60*60*1000) {
                    warranty.setStatus(1);//商业险状态（0：刚提交未审核1：审核通过2：拒绝）
                    inpolicyManager.editwarranty(warranty);
                    return JsonResultUtil.getObjectMessageJson(warranty, "查看保单详情");
                } else {
                    return JsonResultUtil.getObjectMessageJson(warranty, "查看保单详情");
                }
            }
        }
    }


    @ResponseBody
    @RequestMapping("/web/doAddWarranty")
    public  JsonResult c(){
        int i=0;
        return null;
    }

    //得到上一次保险人的信息
    @ResponseBody
    @RequestMapping("/getBeforeWarrantyInfo")
    public JsonResult getBeforeWarrantyInfo(Integer userid){
        InPolicy warranty=inpolicyManager.getWarrantyByuseridAndRecentTime(userid);
        Map map=new HashMap();
        if (warranty==null){
            Member member=memberManager.get(userid);
            try {
                map.put("applicant_name",member.getName());//投保人名称
                map.put("policy_address",member.getAddress());//投保人联系地址
                map.put("policy_mobile","");
                map.put("policy_idcard",member.getMidentity());//投保人组织机构代码或者身份证号码
                map.put("insurant_name","");//被保险人名称
            }catch (Exception e){
                map.put("applicant_name","");//投保人名称
                map.put("policy_address","");//投保人联系地址
                map.put("policy_mobile","");
                map.put("policy_idcard","");//投保人组织机构代码或者身份证号码
                map.put("insurant_name","");//被保险人名称
            }
        }else {
            map.put("applicant_name",warranty.getApplicant_name());//投保人名称
            map.put("policy_address",warranty.getPolicy_address());//投保人联系地址
            map.put("policy_mobile",warranty.getPolicy_mobile());
            map.put("policy_idcard",warranty.getPolicy_idcard());//投保人组织机构代码或者身份证号码
            //map.put("insurant_name","茂名市电白县观珠乡上平山村养殖场");//被保险人名称
            map.put("insurant_name",warranty.getInsurant_name());//被保险人名称
        }
        return JsonResultUtil.getObjectMessageJson(map,"得到上一次保险人的信息");
    }



    //支付成功的保单List
    @RequestMapping("/getwarrantylist")
    @ResponseBody
    public JsonResult getWarrantyList(Integer userid){
        List<Order> orders=orderManager.getByUserIdAndStatus(userid, OrderStatus.ORDER_PAY);
        if (orders==null){
            return JsonResultUtil.getErrorJson("您还没有支付成功的保单");
        }
        List list=new ArrayList();
        for (Order order:orders){
            List<OrderItem> orderItem=orderManager.listGoodsItems(order.getOrder_id());
            if (orderItem==null){
                return JsonResultUtil.getErrorJson("您还没有支付成功的保单");
            }
            for (OrderItem orderItem1:orderItem){
                String policynumber=orderItem1.getUnit();//暂定orderitem,cartitm中的unit字段为policaynumber
                if (policynumber==null){
                    break;
                }
                Map map=new HashMap();
                map.put("policynumber",policynumber);
                map.put("goodsname",orderItem1.getName());
                //map.put("goodsnum",orderItem1.getNum());
                map.put("goodsprice",orderItem1.getPrice());
                map.put("thum", StaticResourcesUtil.transformPathapp(orderItem1.getImage()));
                list.add(map);
            }
        }
        //AlipayCore
        return JsonResultUtil.getObjectMessageJson(list,"支付成功的保单List");
    }


    /**
     * 创建保单号（日期+两位随机数）
     */
    private String createSn(){
        boolean isHave = true;  //数据库中是否存在该保单
        String sn = "";			//保单号

        //如果存在当前保单
        while(isHave) {
            StringBuffer  snSb = new StringBuffer("PLAY2018") ;
            snSb.append(DateUtil.getDateline()+"");
            snSb.append(new Random().nextInt(100-10)+10);
            String sql = "SELECT count(*) FROM rbt_inpolicy WHERE warranty_number = '" + snSb.toString() + "'";
            int count = this.daoSupport.queryForInt(sql);
            if(count == 0) {
                sn = snSb.toString();
                isHave = false;
            }
        }
        return sn;
    }



}
